﻿using MDMAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace MDMAPI.Controllers
{
    [CrossSite]
  
    public class ContactController : ApiController
    {
        private static readonly IContactRep provider = new ContactRep();

        /// <summary>
        /// 查询所有联系人
        /// </summary>
        /// <returns></returns>
        //public IEnumerable<Contact> GetAllContact()
        //{
        //    return provider.GetListAll();
        //}

       // [Route("GetAllContact1")]
        public string GetAllContact1()
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Serialize( provider.GetListAll());
        }


        /// <summary>
        /// 根据编号获得联系人
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Contact GetContact(int id)
        {
            Contact contact = provider.GetByID(id);
            if (contact==null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return contact;
        }

        /// <summary>
        /// 根据性别查询
        /// </summary>
        /// <param name="sex"></param>
        /// <returns></returns>
        public IEnumerable<Contact> GetListBySex(string sex)
        {
            return provider.GetListAll().Where(c=>c.Sex==sex);
        }

        /// <summary>
        /// 添加联系人
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        public Contact PostContact(Contact contact)
        {
            contact = provider.Add(contact);
            return contact;
        }

        /// <summary>
        /// 添加联系人
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        public HttpResponseMessage PostContact1(Contact contact)
        {
            contact = provider.Add(contact);
            HttpResponseMessage response = Request.CreateResponse<Contact>(HttpStatusCode.Created, contact);
            string uri = Url.Link("",new  {id=contact.ID });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void putContact(int id,Contact contact)
        {
            contact.ID = id;
            bool flag = provider.Update(contact);
            if (!flag)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public void DeleteContact(int id)
        {
            provider.Remove(id);
            throw new HttpResponseException(HttpStatusCode.NoContent);
        }
    }
}
